/**.
 *
 */
package com.ww.companyCabinetSystem.business.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.ww.companyCabinetSystem.business.IAdminBusiness;
import com.ww.companyCabinetSystem.constant.BaseConstant;
import com.ww.companyCabinetSystem.dao.IAdminDao;
import com.ww.companyCabinetSystem.model.bo.MAdminBo;
import com.ww.companyCabinetSystem.model.vo.ResultVo;
import com.ww.companyCabinetSystem.utils.MD5Util;
import com.ww.companyCabinetSystem.utils.StringUtil;

/**.
 * com.ww.companyCabinetSystem.business.impl
 * TODO
 * @author veloster
 * 下午3:03:13
 */
@Component("adminBusiness")
public class AdminBusinessImpl extends BaseBusinessImpl implements IAdminBusiness {
	
	/**.
	 * adminDao
	 */
	@Resource(name = "adminDao")
	private IAdminDao adminDao;

	/* (non-Javadoc)
	 * @see com.ww.companyCabinetSystem.business.IAdminBusiness#regist(com.ww.companyCabinetSystem.model.bo.MAdminBo)
	 */
	@Override
	public ResultVo regist(MAdminBo bo) {
		if (bo == null || StringUtil.strIsNullOrEmpty(bo.getUsername()) || StringUtil.strIsNullOrEmpty(bo.getPassword())) {
			return null;
		}
		ResultVo vo = new ResultVo();
		//先查询一次数据库是有有该用户存在
		MAdminBo adminBo = new MAdminBo();
		adminBo.setUsername(bo.getUsername());
		List<MAdminBo> list = adminDao.selectByConfitions(adminBo);
		if (list != null && list.size()!= 0) {
			vo.setFlag(false);
			vo.setStatusCode(BaseConstant.REGISTINFO_USEREXITS);
			return vo;
		}
		String password = bo.getPassword();
		bo.setPassword(MD5Util.md5(password));
		//使用md5加密
		boolean flag = adminDao.insertAdmin(bo);
		vo.setFlag(flag);
		if (!flag) {
			vo.setStatusCode(BaseConstant.REGISTINFO_INSERTERROR);
		}
		return vo;
	}

	
	@Override
	public ResultVo<MAdminBo> login(MAdminBo bo) {
		if (bo == null || StringUtil.strIsNullOrEmpty(bo.getUsername()) || StringUtil.strIsNullOrEmpty(bo.getPassword())) {
			return null;
		}
		ResultVo<MAdminBo> result = new ResultVo<MAdminBo>();
		MAdminBo adminBo = new MAdminBo();
		adminBo.setUsername(bo.getUsername());
		List<MAdminBo> list = adminDao.selectByConfitions(adminBo);
		if (list == null || list.size() == 0) {
			result.setFlag(false);
			return result;
		}
		//取出第一条记录
		MAdminBo resultBo = list.get(0);
		//先看是否有用户权限的传入
		if (bo.getRole() != null) {
			//需要判断用户权限
			if (bo.getRole() != resultBo.getRole()) {
				result.setFlag(false);
				return result;
			}
		}
		//判断密码是否一致
		if (!MD5Util.md5(bo.getPassword()).equals(resultBo.getPassword())) {
			result.setFlag(false);
			return result;
		}
		result.setFlag(true);
		result.setContent(resultBo);
		return result;
	}
}
